import React, { Component } from 'react';
import {Row, Col, Drawer, message} from 'antd';
import "./ Calculator.css";
import History from "./History"
import history from "./History";

class Calculator extends Component {
    constructor(props) {
        super(props);
        this.state = {
            text: "",
            history: [],
            visible: false,
            turn: true
        }
    }

    showDrawer = () => {
        this.setState({
            visible: true,
        });
    };

    onClose = () => {
        this.setState({
            visible: false,
        });
    };

    handleClick = (e) => {
        let oldStr = this.state.text
        const newStr = e.target.innerText
        let resStr = ""
        switch (newStr){
            case "=":
                if(this.state.text === ""){
                    break
                }
                this.handleCalculate()
                break
            case "+":
            case "-":
            case "*":
            case "/":
                this.setState({
                    turn: true
                })
                if(this.state.text[this.state.text.length-1] === " "){
                    oldStr = oldStr.slice(0, -3) // 移除最后算数符号
                }
                else if(this.state.text === ""){
                    break
                }
                resStr = oldStr + " " + newStr + " "
                break
            case "n!":
                if(oldStr[oldStr.length-1] === "^"){
                    resStr = oldStr
                }
                resStr = this.state.turn?oldStr + `!`: oldStr
                this.setState({
                    turn: false
                })
                break
            case "sin":
                if (oldStr[oldStr.length - 1] === " " | oldStr === ""){
                    resStr = this.state.turn?oldStr + `sin()`: oldStr
                    this.setState({
                        turn: false
                    })
                } else {
                    resStr = oldStr
                }
                break
            case "%":
                if(oldStr[oldStr.length-1] === ")" | oldStr[oldStr.length-1] === "%" | oldStr[oldStr.length-1] === "!"){
                    resStr = oldStr
                    break
                }
                resStr = oldStr + newStr
                break
            case "log":
                if (oldStr[oldStr.length - 1] === " " | oldStr === ""){
                    resStr = this.state.turn?oldStr + `log()`: oldStr
                    this.setState({
                        turn: false
                    })
                } else {
                    resStr = oldStr
                }
                break
            case "^":
                if(this.state.text === "" | !this.state.turn){
                    resStr = oldStr
                    break
                }
            default:
                resStr = this.state.turn ? oldStr + newStr : this.addNum(oldStr, newStr)
        }
        this.setState(prevState => ({
            text: resStr
        }));
    }

    handleClear = () => {
        this.setState({ text: "", turn: true });
    }

    addNum(oldStr, newStr){
        return oldStr[oldStr.length-1] !== "!"?oldStr.slice(0, -1) + newStr + ")":oldStr.slice(0, -1) + newStr + "!"
    }

    getAns(record){
        if(record.includes("sin")){
            return this.handleTrigonometric(record.slice(4, -1))
        } else if(record.includes("!")){
            return this.handleFactorial(record.slice(0, -1))
        } else if(record.includes("log")){
            return this.logAble(record.slice(4, -1))
        } else if(record.includes("%")) {
            return this.handlePercentage(record.slice(0, -1))
        }
    }

    handleBackspace = () => {
        if(this.state.text === ""){
            return
        }
        if(this.state.text[this.state.text.length-1] === " "){
            this.setState(prevState => ({
                text: prevState.text.slice(0, -3) // 移除最后一个字符
            }));
        }
        else if(!this.state.turn){
            if(this.state.text[this.state.text.length-2] === "("){
                this.setState(prevState => ({
                    text: prevState.text.slice(0, -5), // 移除最后一个字符
                    turn: true
                }));
            }
            else if(this.state.text[this.state.text.length-1] === "!"){
                if(this.state.text[this.state.text.length-1] === " " | this.state.text === "!"){
                    this.setState(prevState => ({
                        text: prevState.text.slice(0, -1), // 移除最后一个字符
                        turn: true
                    }));
                }
                else{
                    this.setState(prevState => ({
                        text: prevState.text.slice(0, -2) + "!" // 移除最后一个字符
                    }));
                }
            }else{
                this.setState(prevState => ({
                    text: prevState.text.slice(0, -2) + ")" // 移除最后一个字符
                }));
            }
        }
        else{
            this.setState(prevState => ({
                text: prevState.text.slice(0, -1) // 移除最后一个字符
            }));
        }
    }

    handlePercentage = (oldStr) => {
        if (oldStr === ""){
            return 0
        }
        return Number(oldStr)/100
    }

    handleFactorial(oldStr) {
        if(oldStr === ""){
            return 0
        }
        let ans = 1;
        for (let i=1; i<=Number(oldStr); i++){
            ans*=i;
        }
        let resStr = ans.toString()
        return resStr;
    }

    logAble(oldStr){
        if (oldStr === ""){
            return 0
        }
        const num = Number(oldStr)
        return Math.log(num)
    }

    handleTrigonometric(oldStr){
        if (oldStr === ""){
            return 0
        }
        console.log(oldStr)
        return Math.sin(Number(oldStr) * (Math.PI / 180)).toFixed(5).toString()
    }

    handleCalculate = () => {
        let str = this.state.text
        if(str[str.length-1] === " "){
            str = str.slice(0, -3)
        }
        const strList = str.split(" ")
        const midResult = []
        const operator = []
        let res = 0
        strList.forEach((item, index) => {
            if(item.includes("^")){
                const str = item.split("^").map(Number)
                const verifyStr = str.join("^");
                if(item !== verifyStr){
                    message.error("输入错误")
                }
                let last = str[str.length-1]
                for (let i = str.length-2; i>=0; i--){
                    last = Math.pow(str[i], last)
                }
                strList[index] = last.toString()
            }
            else if(item.includes("sin") | item.includes("log") | item.includes("!") | item.includes("%")){
                strList[index] = this.getAns(item).toString()
            }
        })
        strList.forEach((item, index) => {
            if (!isNaN(Number(item))){
                midResult.push(Number(item))
            }
            else if ("*/".includes(item)) {
                const res = (item === "*") ? midResult.pop() * Number(strList.splice(index + 1, 1)[0]) : midResult.pop() / Number(strList.splice(index + 1, 1)[0])
                midResult.push(res)
            }
            else{
                operator.push(item)
            }
        })
        res = midResult[0]
        operator.forEach((item, index) => {
            res += item==="+"?midResult[index+1]:-midResult[index+1]
        })
        let fin = str + " = " + res.toString()
        this.pushToHistory(fin)
    }

    handleDelete = (record) => {
        const reHistory = this.state.history.filter(item => item.key !== record)
        this.setState({
            history: reHistory
        })
    }

    reCalculator = (record) => {
        this.setState({
            text: record
        })
        this.onClose()
    }

    pushToHistory = (fin) => {
        let oldHistory = this.state.history
        const date = new Date()
        const newDo = {
            key: Date.now().toString(),
            formula: fin,
            time: `${date.toLocaleDateString()}-${date.toLocaleTimeString()}`
        }
        this.setState({
            text: fin,
            history: [newDo, ...oldHistory]
        });
    }

    render() {
        return (
            <div id="container">
                <input id="area" value={this.state.text} readOnly />
                <div id="buttonContainer">
                    <Row className="itemRow" type="flex" justify="center">
                        <Col className="do" span={5} onClick={this.handleClear}>AC</Col>
                        <Col className="do" span={5} onClick={this.handleBackspace}>Back</Col>
                        <Col className="do" span={5} onClick={this.handleClick}>%</Col>
                        <Col className="operator" span={5} onClick={this.handleClick}>/</Col>
                        <Col className="operator" span={4} onClick={this.handleClick}>^</Col>
                    </Row>
                    <Row className="itemRow" type="flex" onClick={this.handleClick}  justify="center">
                        <Col className="num" span={5}>1</Col>
                        <Col className="num" span={5}>2</Col>
                        <Col className="num" span={5}>3</Col>
                        <Col className="operator" span={5}>*</Col>
                        <Col className="operator" span={4} onClick={this.handleClick}>sin</Col>
                    </Row>
                    <Row className="itemRow" onClick={this.handleClick} type="flex" justify="center">
                        <Col className="num" span={5}>4</Col>
                        <Col className="num" span={5}>5</Col>
                        <Col className="num" span={5}>6</Col>
                        <Col className="operator" span={5}>+</Col>
                        <Col className="operator" span={4} onClick={this.handleClick}>n!</Col>
                    </Row>
                    <Row className="itemRow" onClick={this.handleClick} type="flex" justify="center">
                        <Col className="num" span={5}>7</Col>
                        <Col className="num" span={5}>8</Col>
                        <Col className="num" span={5}>9</Col>
                        <Col className="operator" span={5} >-</Col>
                        <Col className="operator" span={4} onClick={this.handleClick}>log</Col>
                    </Row>
                    <Row className="itemRow" type="flex" justify="center">
                        <Col className="num" onClick={this.handleClick} span={12}>0</Col>
                        <Col className="num" onClick={this.handleClick} span={6}>.</Col>
                        <Col className="compute" onClick={this.handleCalculate} span={6}>=</Col>
                    </Row>
                </div>
                <div id="history">
                    <h3 onClick={this.showDrawer}>History</h3>
                </div>
                <Drawer
                    title="历史记录"
                    placement="right"
                    closable={false}
                    onClose={this.onClose}
                    visible={this.state.visible}
                    width={500}
                >
                    <History dataSource={this.state.history} handleDelete={this.handleDelete} reCalculator={this.reCalculator}/>
                </Drawer>
            </div>
        )
    }
}

export default Calculator;